package com.example.hongyu.avtt.ui.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;


import com.example.hongyu.avtt.R;
import com.example.hongyu.avtt.event.Event;
import com.example.hongyu.avtt.listener.OnItemClickListener;
import com.example.hongyu.avtt.model.Picture;
import com.example.hongyu.avtt.model.entity.BaseResponse;
import com.example.hongyu.avtt.network.BaseObserver;
import com.example.hongyu.avtt.network.RetrofitHelper;
import com.example.hongyu.avtt.network.RxUtil;
import com.example.hongyu.avtt.network.api.AppInfoApi;
import com.example.hongyu.avtt.ui.activity.PictureShowActivity;
import com.example.hongyu.avtt.ui.adapter.PictureListAdapter;
import com.example.hongyu.avtt.ui.base.BaseFragment;
import com.example.hongyu.avtt.ui.widget.MyItemDecoration;
import com.example.hongyu.avtt.ui.widget.ToastTool;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

public class ImageFragment extends BaseFragment {
    private final String TAG="VideoFragment";
    @BindView(R.id.recycle_view)
    XRecyclerView xRecyclerView;

    List<Picture> pictures=new ArrayList<>();
    PictureListAdapter pictureListAdapter;

    private int pageIndex=1;
    private int pageSize=100;
    //判断是否已进行过加载，避免重复加载
    private boolean isLoad=false;
    //判断当前fragment是否可见
    private boolean isVisibleToUser = false;
    //判断当前fragment是否回调了resume
    private boolean isResume = false;
    int dataSize=0;
    @Override
    protected View getContentView(LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(R.layout.fragment_image, container, false);
    }

    @Override
    protected void initView() {
        initRecyclerView(xRecyclerView);
    }

    @Override
    protected void initData() {

    }
    /**
     * 初始化RecyclerView
     *
     * @param recyclerView 主控件
     */
    private void initRecyclerView(XRecyclerView recyclerView) {
        recyclerView.setPullRefreshEnabled(true);
        recyclerView.setHasFixedSize(true); // 设置固定大小
        initRecyclerLayoutManager(recyclerView); // 初始化布局
        initRecyclerAdapter(recyclerView); // 初始化适配器
        initItemDecoration(recyclerView); // 初始化装饰
        initItemAnimator(recyclerView); // 初始化动画效果
    }
    private void initRecyclerAdapter(XRecyclerView recyclerView) {
        pictureListAdapter = new PictureListAdapter(this.getContext(),pictures);
        recyclerView.setAdapter(pictureListAdapter);
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                pageIndex=1;
                htppGetHtmlList(pageIndex, true);
            }

            @Override
            public void onLoadMore() {
                pageIndex++;
                htppGetHtmlList(pageIndex, false);
            }
        });
        pictureListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ToastTool.show(""+position);
                Picture vedio=pictures.get(position-1);
                String url=vedio.getPath();
                String name=vedio.getName();
                mBundle=getBundle();
                if (mBundle==null){
                    mBundle=new Bundle();
                }
                mBundle.putString("PLAYURL",url);
                mBundle.putString("PLAYNAME",name);
              sendIntent(PictureShowActivity.class,mBundle);

            }
        });
    }
    private void initRecyclerLayoutManager(XRecyclerView recyclerView) {
        // 错列网格布局
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL));
    }
    private void initItemDecoration(XRecyclerView recyclerView) {
        recyclerView.addItemDecoration(new MyItemDecoration(this.getContext()));
    }
    private void initItemAnimator(XRecyclerView recyclerView) {
        recyclerView.setItemAnimator(new DefaultItemAnimator()); // 默认动画
    }
    @Override
    protected void onEventProcess(Event event) {

    }
    @Override
    public void onResume() {
        super.onResume();
        isResume=true;
        lazyLoad();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.i(TAG, "setUserVisibleHint: "+isVisibleToUser+""+this);
        this.isVisibleToUser=isVisibleToUser;
        lazyLoad();
    }

    private void lazyLoad() {
        if (!isLoad&&isVisibleToUser&&isResume){
            htppGetHtmlList(pageIndex,true);
            isLoad=true;
        }
    }

    @SuppressLint("AutoDispose")
    private void htppGetHtmlList(int index, boolean isRefresh) {
        RetrofitHelper.create(AppInfoApi.class)
                .pictureList("","",pageIndex,pageSize)
                .compose(RxUtil.observervableToMain())
                .subscribe( new BaseObserver<List<Picture>>(getLoadingDialog()){
                    @Override
                    public void onSuccess(BaseResponse<List<Picture>> response) {
                        if (response!=null&&response.getData()!=null){
                            if(isRefresh){
                                pictures.clear();
                                xRecyclerView.refreshComplete();
                            }else {
                                dataSize=response.getData().size();
                                xRecyclerView.loadMoreComplete();


                            }

                            pictures.addAll(response.getData());

                            pictureListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if(isRefresh){
                            xRecyclerView.refreshComplete();
                        }else {
                            xRecyclerView.loadMoreComplete();
                        }
                    }
                });
    }

    /**
     * 获取日期的前一天
     *
     * @param date 日期
     * @param i    偏离
     * @return 新的日期
     */
    private static Date getBeforeDay(Date date, int i) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, i * (-1));
        return calendar.getTime();
    }


}

